package com.ruoyi.web.controller.course;

import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollectionUtil;
import com.doudou.core.container.ListUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.ruoyi.course.domain.*;
import com.ruoyi.course.service.ICourseExRecordService;
import com.ruoyi.course.service.ICourseTrainService;
import com.ruoyi.course.service.ICourseWareService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.course.service.ICourseStudyRecordService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 课程学习记录Controller
 *
 * @author zzx
 * @date 2023-04-05
 */
@Api("课程学习记录")
@RestController
@RequestMapping("/course/record")
public class CourseStudyRecordController extends BaseController {
    @Autowired private ICourseStudyRecordService courseStudyRecordService;
    @Autowired private ICourseExRecordService courseExRecordService;
    @Autowired private ICourseWareService courseWareService;
    @Autowired private ICourseTrainService courseTrainService;

    /**
     * 根据课程返回学习记录
     */
    @GetMapping("/info/{trainId}")
    @ApiOperation("根据课程返回学习记录")
    public AjaxResult info(@PathVariable("trainId")Long trainId) {
        List<CourseStudyRecord> list = courseStudyRecordService.selectCourseStudyRecordList(CourseStudyRecord.builder().
                userId(getUserId()).
                deptId(getDeptId()).
                trainId(trainId).
                build());
        return AjaxResult.success(ObjectUtil.isNotEmpty(list) ? list.get(0) : new CourseStudyRecord());
    }

    /**
     * 查询当前用户的学习记录
     */
    @GetMapping("/my-list")
    @ApiOperation("查询当前用户的学习记录")
    public TableDataInfo myList() {
        Long userId = getUserId();
        Long deptId = getDeptId();
        List<CourseStudyRecord> list = courseStudyRecordService.selectCourseStudyRecordList(CourseStudyRecord.builder().userId(userId).deptId(deptId).build());
        try{
            for (CourseStudyRecord courseStudyRecord : list) {
                //查询出课程下所有课件
                CourseTrain courseTrain = CourseTrain.builder().deptId(getDeptId()).id(courseStudyRecord.getTrainId()).build();
                List<CourseTrain> courseTrainList = courseTrainService.selectCourseTrainListAll(courseTrain);
                List<CourseWare> courseWareListAll = ListUtil.list(true);
                String image = "";
                if (ObjectUtil.isNotEmpty(courseTrainList)){
                    courseTrain = courseTrainList.get(0);
                    if (ObjectUtil.isNotEmpty(courseTrain.getSectionList())){
                        for (CourseTrainSection courseTrainSection : courseTrain.getSectionList()) {
                            if (ObjectUtil.isNotEmpty(courseTrainSection.getCourseWareList())){
                                image = courseTrainSection.getCourseWareList().get(0).getThumbnail();
                                courseWareListAll.addAll(courseTrainSection.getCourseWareList());
                            }
                        }
                    }
                }
                courseStudyRecord.setReservedOne(image);
                if (!courseWareListAll.isEmpty()){
                    courseStudyRecord.setWareTotal(courseWareListAll.size());
                    for (CourseWare courseWare : courseWareListAll) {
                        //获取到该课件下我的做题记录
                        CourseExRecord exRecord = CourseExRecord.builder().userId(userId).deptId(deptId).wareId(courseWare.getId()).build();
                        List<CourseExRecord> courseExRecords = courseExRecordService.selectCourseExRecordList(exRecord);
                        if (ObjectUtil.isNotEmpty(courseExRecords)){
                            exRecord = courseExRecords.get(0);
                            long right = ObjectUtil.isNotEmpty(exRecord.getRight()) ? exRecord.getRight() : 0;
                            int questionSize = ObjectUtil.isNotEmpty(exRecord.getQuestionIds()) ? exRecord.getQuestionIds().size() : 0;
                            courseStudyRecord.addAccuracy(NumberUtil.round((double) right / questionSize * 100,2).doubleValue());
                        }
                    }
                    //成功率 = 所有课件的成绩总和 / 课件总数
                    courseStudyRecord.setAccuracyNumber(NumberUtil.round(courseStudyRecord.getAccuracyNumber() / courseStudyRecord.getWareTotal(),2).doubleValue());
                }
            }
        }catch (Exception e){
            logger.error("",e);
        }
        return getDataTable(list);
    }

    /**
     * 查询课程学习记录列表
     */
    @GetMapping("/list")
    @ApiOperation("查询课程学习记录列表")
    public TableDataInfo list(CourseStudyRecord courseStudyRecord) {
        startPage();
        courseStudyRecord.setDeptId(getDeptId());
        List<CourseStudyRecord> list = courseStudyRecordService.selectCourseStudyRecordList(courseStudyRecord);
        return getDataTable(list);
    }

    /**
     * 导出课程学习列表
     */
    @Log(title = "课程学习记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CourseStudyRecord courseStudyRecord) {
        courseStudyRecord.setDeptId(getDeptId());
        List<CourseStudyRecord> list = courseStudyRecordService.selectCourseStudyRecordList(courseStudyRecord);
        ExcelUtil<CourseStudyRecord> util = new ExcelUtil<CourseStudyRecord>(CourseStudyRecord.class);
        util.exportExcel(response, list, "course_record数据");
    }

    /**
     * 获取课程学习记录详细信息
     */
    @GetMapping(value = "/{id}")
    @ApiOperation("获取课程学习记录详细信息")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(courseStudyRecordService.selectCourseStudyRecordById(id));
    }

    /**
     * 获取当前登录用户的课程学习记录
     */
    @GetMapping("/getUserData")
    @ApiOperation("获取当前登录用户的课程学习记录列表")
    public TableDataInfo getUserData() {
        CourseStudyRecord courseStudyRecord = CourseStudyRecord.builder().userId(getUserId()).build();
        List<CourseStudyRecord> list = courseStudyRecordService.selectCourseStudyRecordList(courseStudyRecord);
        return getDataTable(list);
    }

    /**
     * 新增课程学习记录
     */
    @Log(title = "课程学习记录", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增课程学习记录")
    public AjaxResult add(@RequestBody CourseStudyRecord courseStudyRecord) {
        courseStudyRecord.setDeptId(getDeptId());
        courseStudyRecord.setUserId(getUserId());
        //观看次数加一
        courseWareService.updateWatchCountAdd(courseStudyRecord.getWareId());
        return toAjax(courseStudyRecordService.insertCourseStudyRecord(courseStudyRecord));
    }


    /**
     * 学习记录加一
     */
    @Log(title = "课程学习记录添加", businessType = BusinessType.INSERT)
    @PostMapping("/study")
    @ApiOperation("学习记录加一")
    public AjaxResult addStudy(@Validated @RequestBody CourseStudyRecord courseStudyRecord) {
        try{
            courseStudyRecord.setDeptId(getDeptId());
            courseStudyRecord.setUserId(getUserId());
            Long wareId = courseStudyRecord.getWareId();
            //先查询是否有当前课程下的记录,查询的字段有  用户编号、机构编号、课程编号
            CourseStudyRecord courseStudyRecord1 = courseStudyRecordService.selectCourseStudyRecordByAllId(courseStudyRecord);
            List<Long> studyList;
            if (ObjectUtil.isNotEmpty(courseStudyRecord1)){//修改
                //已学习列表
                studyList = JSONUtil.toList(courseStudyRecord1.getStudyList(), Long.class);
                if (studyList.contains(wareId)){
                    return AjaxResult.success("学习记录已存在");
                }else{
                    studyList.add(wareId);
                    courseStudyRecord1.setStudyTotal(studyList.size());
                    courseStudyRecord1.setStudyList(studyList.toString());
                    //如果条数满足，则学习完成
                    if (studyList.size() == courseStudyRecord1.getWareTotal()){
                        courseStudyRecord1.setEndTime(new Date());
                        courseStudyRecord1.setStatus(2);//已完成
                    }
                    //修改
                    return toAjax(courseStudyRecordService.updateCourseStudyRecord(courseStudyRecord1));
                }
            }else{//新增
                courseStudyRecord.setStartTime(new Date());
                courseStudyRecord.setStatus(1);//已开始
                studyList = ListUtil.list(false, wareId);
                courseStudyRecord.setStudyTotal(studyList.size());
                courseStudyRecord.setStudyList(studyList.toString());
                //添加
                return toAjax(courseStudyRecordService.insertCourseStudyRecord(courseStudyRecord));
            }
        }catch (Exception e){
            logger.error("",e);
        }
        return AjaxResult.error("学习记录添加失败");
    }

    /**
     * 修改课程学习记录
     */
    @Log(title = "课程学习记录", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改课程学习记录")
    public AjaxResult edit(@RequestBody CourseStudyRecord courseStudyRecord) {
        return toAjax(courseStudyRecordService.updateCourseStudyRecord(courseStudyRecord));
    }

    /**
     * 删除课程学习记录
     */
    @Log(title = "课程学习记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation("删除课程学习记录")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(courseStudyRecordService.deleteCourseStudyRecordByIds(ids));
    }
}
